package br.pucrio.inf.tamdera.mapping;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import br.pucrio.inf.tamdera.RulesSpecification;
import br.pucrio.inf.tamdera.TamderaException;
import br.pucrio.inf.tamdera.prolog.PrologRepresentationManager;
import br.pucrio.inf.tamdera.prolog.utils.PrologIntegrationConstants;
import br.pucrio.inf.tamdera.utils.ConverterPrologTamderaUtils;

public class ConceptMappingManagement {


	public ConceptMappingManagement(RulesSpecification spec, PrologRepresentationManager prologManager) {
		super();
		this.spec = spec;
		this.prologManager = prologManager;
	}

	
	private PrologRepresentationManager prologManager;
	
	/* root element of the AST */
	private RulesSpecification spec;


	private final String SOURCE_FORMAT = ".java";

	public HashMap<String, List<String>> doMap() throws TamderaException {

		final List<String> javaClassesNames = extractClassesNamesFromPrologProjectFile();
		
		MappingExtractorVisitor visitor = new MappingExtractorVisitor( javaClassesNames, prologManager );
		visitor._extractConceptMapping(spec);

		return visitor.getConceptMapping();
	}

	@SuppressWarnings("unused")
	private void extractClassesNamesFromSourceProject(File sourceDirectory,
			List<String> javaClassesNames, String fileName) 
	{

		String[] childrenFiles = sourceDirectory.list();
		for (String childFileStr : childrenFiles )
		{
			String oldFileName = fileName;
			
			File childFile = new File( sourceDirectory.getAbsolutePath() + File.separator + childFileStr);
			if ( childFile.isDirectory() )
			{
				fileName = includeSeparator(fileName, childFile.getName()) ;
				extractClassesNamesFromSourceProject(childFile, javaClassesNames, fileName);
			}
			else if (childFile.isFile() && childFile.getAbsolutePath().endsWith(SOURCE_FORMAT))
			{
				fileName  = includeSeparator(fileName, childFile.getName());
				fileName = fileName.substring(0, fileName.length() - SOURCE_FORMAT.length());
				javaClassesNames.add( fileName );
			}
			
			fileName = oldFileName;
		}

	}
	
	/**
	 * extract all classes from the prolog file and inserts in the list
	 */
	private List<String>  extractClassesNamesFromPrologProjectFile( ) 
	{
		final List<String> prologClasses =  prologManager.extractAllClassesFromPrologProjectFile(  );
		return ConverterPrologTamderaUtils.getConvertedNamesOfPrologClasses( prologClasses );
		
	}
	

	/**
	 * It appends the directory separator pattern during the building of the class name
	 * @param file
	 * @param name
	 * @return
	 */
	private String includeSeparator(String file, String name)
	{
		if (file.equals(""))
		{
			return name;
		}
		file += PrologIntegrationConstants.PACKAGE_SEPARATOR_IN_TAMDERA_DSL + name;
		return file;
	}
}
